﻿using DoNet.Common.Helper;
using DoNet.WechatPay.Enums;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace DoNet.WechatPay.V2
{
    /// <summary>
    /// 微信支付请求
    /// </summary>
    public class WechatPayData : ParameterBase
    {
        /// <summary>
        /// 微信支付key
        /// </summary>
        private string Key = string.Empty;
        /// <summary>
        /// 签名类型
        /// </summary>
        public PaySignType SignType = PaySignType.MD5;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="key"></param>
        /// <param name="signType"></param>
        public WechatPayData(string key, PaySignType signType = PaySignType.MD5) : base()
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                Key = key;
            }
            SignType = signType;
        }

        /// <summary>
        /// 获取加密字符串
        /// </summary>
        /// <param name="signType"></param>
        /// <returns></returns>
        public string CreateSign()
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (Parameters.Count > 0)
            {
                foreach(var item in Parameters)
                {
                    if ("sign".CompareTo(item.Key) == 0 || "key".CompareTo(item.Key) == 0)
                    {
                        continue;
                    }

                    var text = item.Value;
                    if (text == null)
                    {
                        continue;
                    }

                    string text2 = (string)text;
                    if (string.IsNullOrWhiteSpace(text2))
                    {
                        continue;
                    }

                    stringBuilder.Append(item + "=" + text2 + "&");
                }
                stringBuilder.Append("key=" + Key);

                if (SignType == PaySignType.MD5)
                {
                    //MD5加密字符串
                    return EncryptHelper.GetMD5(stringBuilder.ToString()).ToUpper();
                }
                else if (SignType == PaySignType.HMACSHA256)
                {
                    //HmacSha256加密字符串
                    return EncryptHelper.GetHmacSha256(stringBuilder.ToString(), Key).ToUpper();
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 检测签名是否正确
        /// </summary>
        /// <returns>正确返回true，错误返回false</returns>
        public bool CheckSign()
        {
            if(!IsSet("sign"))
            {
                var sign = GetValue("sign")?.ToString();
                if (!string.IsNullOrWhiteSpace(sign))
                {
                    //获取接收到的签名
                    string return_sign = sign;
                    //在本地计算新的签名
                    string cal_sign = CreateSign();
                    if (cal_sign == return_sign)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 参数转成xml字符串
        /// </summary>
        /// <returns></returns>
        public string ParseXml()
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (Parameters.Count > 0)
            {
                stringBuilder.Append("<xml>");
                foreach (string key in Parameters.Keys)
                {
                    if (!string.IsNullOrWhiteSpace(key))
                    {
                        var text = Parameters[key];
                        if (text != null)
                        {
                            string text2 = (string)text;
                            if (text2 != null && Regex.IsMatch(text2, "^[0-9.]$"))
                            {
                                stringBuilder.Append("<" + key + ">" + text2 + "</" + key + ">");
                            }
                            else
                            {
                                stringBuilder.Append("<" + key + "><![CDATA[" + text2 + "]]></" + key + ">");
                            }
                        }
                    }
                }
                stringBuilder.Append("</xml>");
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// xml字符串转成SortedDictionary
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public SortedDictionary<string, object> FromXml(string xml)
        {
            if (!string.IsNullOrEmpty(xml))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.XmlResolver = null;

                xmlDoc.LoadXml(xml);
                var xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
                if (xmlNode != null)
                {
                    XmlNodeList nodes = xmlNode.ChildNodes;
                    foreach (XmlNode xn in nodes)
                    {
                        XmlElement xe = (XmlElement)xn;
                        Parameters[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
                    }
                }
            }
            return Parameters;
        }
    }
}
